var errorVisible = false;
var canSubmit = false;

function validateForm() {
  canSubmit = true;
  $(".required").each(function(event) { validateElement(this,event); });

  if(canSubmit) {
    $('input[type="submit"]').removeAttr('disabled');
    hideError();
  } else {
    $('input[type="submit"]').attr('disabled','disabled');
    showError();
  }
}

function validateElement(element, event) {
  var validElement = true;
  var errorMessage = "";
  if (isEmpty(element)) { 
    errorMessage = "Please fill in all the required fields."; 
    $("#error-message-window").text(errorMessage);
    validElement = false;
  }

  canSubmit = canSubmit && validElement;
}

function isEmpty(elem) {
  var value = $(elem).val();
  value = value.replace(/^\s+|\s+$/g,''); //remove whitespace
    if (value == null || value == "") return true;
    else return false;
}

function showError() { $("#error-message-window").fadeIn(function(){errorVisible = true;});}
function hideError() { $("#error-message-window").fadeOut(function(){errorVisible = false;});}